package com.xuxueli.applyModules.service;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Font;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.metadata.TableStyle;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.xuxueli.applyModules.entity.ExportAppVo;
import com.xuxueli.applyModules.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

@Service
@Slf4j
public class ExportService {
    /**
     * 用户洞察中心App导出
     * long start = System.currentTimeMillis()//单位毫秒ms
     * long start = System.currentTimeMillis() / 1000 //单位秒s
     * @param response
     */
    public void downLoadInsightApp(HttpServletResponse response) {
        String fileName="用户洞察中心App报表"+ DateUtils.format(new Date(),"yyyyMMddHHmmss");
        String sheetName="用户洞察中心App报表";
        try {
            OutputStream out = getOutputStream(response, fileName, ExcelTypeEnum.XLSX);
            //这里指定需要表头，因为model通常包含表信头息
            ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
            //写第一个sheet,数据全是List<String> 无模型映射关系
            Sheet sheet = new Sheet(1, 0, ExportAppVo.class);
            //设置自适应宽度
            sheet.setAutoWidth(Boolean.TRUE);
            //设置表格样式
            sheet.setTableStyle(createTableStyle());
            //设置sheetName
            sheet.setSheetName(sheetName);

            //分页查询数据
            int pageNumber = 1;
            int pageSize = 5000;
            int dataLength = pageSize;
            long start = System.currentTimeMillis() / 1000;//单位秒
            Map<String, Object> condition=new HashMap<>();
            List<ExportAppVo> resultList=null;//置list为空，清空内存
            while(dataLength == pageSize){
                int startIndex = (pageNumber - 1) * pageSize;
                condition.put("pageNo", startIndex);
                condition.put("pageSize", pageSize);
                resultList=queryInsightApp(condition);
                if(resultList==null || resultList.isEmpty()){
                    //写数据
                    writer.write(resultList, sheet);
                    break;
                }
                dataLength = resultList.size();
                pageNumber++;
                //写数据
                writer.write(resultList, sheet);
            }
            //关闭writer的输出流
            writer.finish();
            long end = System.currentTimeMillis() / 1000;
            log.info("导出耗时：" + (end - start) +" 秒");
        } catch (Exception e) {
            log.error("导出异常",e);
        }
    }


    /**
     * 数据库查询
     * @param condition
     * @return
     */
    private List<ExportAppVo> queryInsightApp(Map<String,Object> condition){
        List<ExportAppVo> list = new ArrayList<>();
        return list;
    }
    /**
     * 得到流
     * @param response 响应
     * @param fileName 文件名
     * @param excelTypeEnum excel类型
     * @return
     */
    private OutputStream getOutputStream(HttpServletResponse response, String fileName, ExcelTypeEnum excelTypeEnum) {
        try {
            // 设置响应输出的头类型
            if (Objects.equals(".xls", excelTypeEnum.getValue())) {
                //导出xls格式
                response.setContentType("application/vnd.ms-excel;charset=GBK");
            } else if (Objects.equals(".xlsx", excelTypeEnum.getValue())) {
                //导出xlsx格式
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=GBK");
            }
            // 设置下载文件名称(注意中文乱码)
            response.addHeader("Content-Disposition", "attachment;filename=" + new String((fileName).getBytes("GB2312"), "ISO8859-1") + excelTypeEnum.getValue());
            response.addHeader("Pragma", "No-cache");
            response.addHeader("Cache-Control", "No-cache");
            response.setCharacterEncoding("utf8");
            return response.getOutputStream();
        } catch (IOException e) {
            log.error("EasyExcelUtil-->getOutputStream exception:", e);
        }
        return null;
    }

    /**
     * 设置表格样式
     * @return
     */
    private TableStyle createTableStyle() {
        TableStyle tableStyle = new TableStyle();
        Font headFont = new Font();
        headFont.setBold(true);
        headFont.setFontHeightInPoints((short) 20);
        headFont.setFontName("楷体");
        tableStyle.setTableHeadFont(headFont);
        tableStyle.setTableHeadBackGroundColor(IndexedColors.LIGHT_GREEN);
        Font contentFont = new Font();
        contentFont.setFontHeightInPoints((short) 12);
        contentFont.setFontName("黑体");
        tableStyle.setTableContentFont(contentFont);
        return tableStyle;
    }

}
